package ui;

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import model.Customer;
import service.CustomerService;
import service.AttributeService;
import utils.*;

import java.util.ArrayList;
import java.util.List;

public class CustomerListPage extends Application {

    private PdfUtil pdfUtil = new PdfUtil();
    private List<Customer> selectedCustomers = new ArrayList<>();
    private List<CheckBox> customerCheckBoxes = new ArrayList<>();
    private List<Customer> allCustomers;
    private CustomerService customerService = new CustomerService();

    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("客户列表页");

        VBox vbox = new VBox();
        vbox.setPadding(new Insets(10));
        vbox.setSpacing(10);
        vbox.getStyleClass().add("root");

        // 获取所有客户并存储在类变量中
        allCustomers = customerService.getAllCustomers();
        selectedCustomers.clear(); // 清空之前的选择

        for (Customer customer : allCustomers) {
            HBox row = new HBox();
            row.setSpacing(10);
            row.getStyleClass().add("hbox");

            // 左侧复选框
            CheckBox checkBox = new CheckBox();
            final Customer currentCustomer = customer; // 创建final变量用于lambda表达式
            checkBox.selectedProperty().addListener((observable, oldValue, newValue) -> {
                if (newValue) {
                    if (!selectedCustomers.contains(currentCustomer)) {
                        selectedCustomers.add(currentCustomer);
                    }
                } else {
                    selectedCustomers.remove(currentCustomer);
                }
            });
            customerCheckBoxes.add(checkBox);
            checkBox.getStyleClass().add("check-box");

            // 中间显示客户名称
            Label nameLabel = new Label(customer.getCustomerName());
            HBox.setHgrow(nameLabel, Priority.ALWAYS);
            nameLabel.setMaxWidth(Double.MAX_VALUE);
            nameLabel.getStyleClass().add("label");

            // 右侧"详情"按钮
            Button detailButton = new Button("详情");
            detailButton.setOnAction(e -> {
                // 使用新创建的CustomerDetailPage类
                CustomerDetailPage detailPage = new CustomerDetailPage(customer);
                try {
                    detailPage.start(new Stage());
                    primaryStage.close();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            });
            detailButton.getStyleClass().add("button");

            // 右侧"修改"按钮
//            Button editButton = new Button("修改");
//            editButton.setOnAction(e -> {
//                // 使用新创建的EditCustomerPage类
//                EditCustomerPage editPage = new EditCustomerPage(customer);
//                try {
//                    editPage.start(new Stage());
//                    primaryStage.close();
//                } catch (Exception ex) {
//                    ex.printStackTrace();
//                }
//            });
//            editButton.getStyleClass().add("button");

            row.getChildren().addAll(checkBox, nameLabel, detailButton);
            vbox.getChildren().add(row);
        }

        // 滚动条
        ScrollPane scrollPane = new ScrollPane(vbox);
        scrollPane.setFitToWidth(true);
        scrollPane.getStyleClass().add("scroll-pane");

        // 创建按钮区域
        Button exportPdfButton = new Button("导出PDF");
        exportPdfButton.setOnAction(e -> {
            if (selectedCustomers.isEmpty()) {
                CommonUtil.showAlert("提示", "请先选择要导出的客户！", Alert.AlertType.WARNING);
                return;
            }
            // 使用新的基于EAV模型的PDF导出功能
            pdfUtil.createCustomerPdfs(selectedCustomers);
        });
        exportPdfButton.getStyleClass().add("export-button");

        Button exportSelectedButton = new Button("导出Excel");
        exportSelectedButton.setOnAction(e -> {
            if (selectedCustomers.isEmpty()) {
                CommonUtil.showAlert("提示", "请先选择要导出的客户！", Alert.AlertType.WARNING);
                return;
            }
            // 使用新的EAV模型导出功能
            ExcelExportUtil.exportCustomersFromEAV(selectedCustomers);
        });
        exportSelectedButton.getStyleClass().add("export-button");

        Button deleteButton = new Button("删除");
        deleteButton.setOnAction(e -> {
            deleteSelectedCustomers();
            primaryStage.close();
        });
        deleteButton.getStyleClass().add("delete-button");

        Button importButton = new Button("导入客户");
        importButton.setOnAction(e -> {
            ExcelImportUtil.readLogisticsExcel();
            CustomerListPage customerListPage = new CustomerListPage();
            customerListPage.start(new Stage());
            primaryStage.close();
        });
        importButton.getStyleClass().add("import-button");

        Button loadButton = new Button("下载模板");
        loadButton.setOnAction(e -> {
            // 直接调用ExcelLoadUtil的模板下载功能
            ExcelLoadUtil.loadLogisticsExcel();
        });
        loadButton.getStyleClass().add("load-button");

        Button addButton = new Button("添加");
        addButton.setOnAction(e -> {
            AddCustomerPage addCustomerPage = new AddCustomerPage(new Stage());
            addCustomerPage.show();
            primaryStage.close();
        });
        addButton.getStyleClass().add("add-button");

        Button backButton = new Button("返回");
        backButton.setOnAction(e -> {
            MenuPage menuPage = new MenuPage();
            menuPage.start(new Stage());
            primaryStage.close();
        });
        backButton.getStyleClass().add("back-button");

        // 全选复选框
        CheckBox selectAllCheckBox = new CheckBox("全选");
        selectAllCheckBox.setOnAction(e -> {
            boolean selectAll = selectAllCheckBox.isSelected();
            selectedCustomers.clear(); // 清空当前选择
            
            for (int i = 0; i < customerCheckBoxes.size(); i++) {
                CheckBox checkBox = customerCheckBoxes.get(i);
                checkBox.setSelected(selectAll);
            }
        });

        // 创建一个HBox来对齐按钮
        HBox bottomButtons = new HBox(11);
        bottomButtons.setPadding(new Insets(111));
        bottomButtons.getChildren().addAll(
            selectAllCheckBox, 
            exportPdfButton,
            exportSelectedButton,
            importButton,
            loadButton,
            deleteButton,
            addButton,
            backButton
        );
        bottomButtons.setAlignment(Pos.CENTER_LEFT);

        VBox root = new VBox(scrollPane, bottomButtons);
        root.setSpacing(10);
        root.getStyleClass().add("root");

        Scene scene = new Scene(root, 1000, 970);
        scene.getStylesheets().add(getClass().getResource("/css/logisticsList.css").toExternalForm());

        primaryStage.setScene(scene);
        primaryStage.show();
    }

    private void deleteSelectedCustomers() {
        if (selectedCustomers.isEmpty()) {
            CommonUtil.showAlert("提示", "未选择任何客户进行删除。", Alert.AlertType.INFORMATION);
            return;
        }

        for (Customer customer : new ArrayList<>(selectedCustomers)) {
            customerService.deleteCustomer(customer.getCustomerId());
        }

        selectedCustomers.clear();
        start(new Stage());
    }
}
